# -*- coding: utf-8 -*-

from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import ImproperlyConfigured
from django.db.models import get_model, Q
from provider.oauth2.models import AccessToken

from Utils import utc_now

class SocialAnimalBackend(ModelBackend):
    def authenticate(self, username=None, password=None,):
        # authenticate user by username or email
        try:
            user = self.user_class.objects.get(
                Q(username=username) | Q(email=username)
            )
            if user.check_password(password):
                return user
        except self.user_class.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            return self.user_class.objects.get(pk=user_id)
        except self.user_class.DoesNotExist:
            return None

    @property
    def user_class(self):
        if not hasattr(self, '_user_class'):
            self._user_class = get_model(*settings.CUSTOM_USER_MODEL.split('.', 2))
            if not self._user_class:
                raise ImproperlyConfigured('Could not get custom user model')
        return self._user_class


class AccessTokenBackend(object):
    """ 
    Authenticate a user via access token.
    """

    supports_inactive_user = True
    
    def authenticate(self, access_token=None):
        try:
            access_token = AccessToken.objects.get(token=access_token,
                expires__gt=utc_now())
            custom_user = self.user_class.objects.get(pk=access_token.user.id)
            return custom_user

        except AccessToken.DoesNotExist:
            return None

    @property
    def user_class(self):
        if not hasattr(self, '_user_class'):
            self._user_class = get_model(*settings.CUSTOM_USER_MODEL.split('.', 2))
            if not self._user_class:
                raise ImproperlyConfigured('Could not get custom user model')
        return self._user_class
